"use strict";
module.exports = async (options = { canCreateTables: false }) => {
    var libRpc = require('lib_rpc');
    await libRpc.rpc.setup();
    return new Promise((resolve, reject) => {
        libRpc.rpc.act('role: config, cmd: getDatabase', (err, result) => {
            if (err) {
                reject(`get database config failure...${err}`);
                return;
            }
            let envConf = result;
            console.log('[libmodels]', `get database config...${JSON.stringify(envConf)}`);
            var fs = require("fs");
            var path = require("path");
            let mysqlConf = envConf;
            let Sequelize = require('sequelize');
            var sequelize = new Sequelize(mysqlConf.schema, mysqlConf.username, mysqlConf.password, {
                host: mysqlConf.host,
                dialect: 'mysql',
                pool: {
                    max: mysqlConf.pool.max,
                    min: mysqlConf.pool.min,
                    idle: mysqlConf.pool.idle,
                },
            });

            var db = {};
            var modelNameOrders = [];
            require('./loadOrders.json')
                .forEach(function (file) {
                    var model = sequelize.import(path.join(__dirname, `${file}.js`));
                    db[model.name] = model;
                    modelNameOrders.push(model.name);
                });
            // fs
            //     .readdirSync(__dirname)
            //     .filter(function (file) {
            //         return (file.indexOf(".") !== 0) && (file !== "index.js");
            //     })
            //     .forEach(function (file) {
            //         var model = sequelize.import(path.join(__dirname, file));
            //         db[model.name] = model;
            //     });

            modelNameOrders.forEach(function (modelName) {
                if ("associate" in db[modelName]) {
                    db[modelName].associate(db);
                }
            });

            if (options.canCreateTables) {
                // modelNameOrders.forEach(function (modelName) {
                //     db[modelName].sync({ force: false });
                // });
                sequelize.sync();
            }

            db.sequelize = sequelize;
            db.Sequelize = Sequelize;

            resolve(db);
        });
    });
};